package com.congwulin.wechat.util.service.vo;

import com.congwulin.wechat.entity.common.SuperVO;
import com.congwulin.wechat.util.EntityConst;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class VOSaveService {
    /**
     * 实体删除服务
     */
    private VODeleteService deleteService;

    /**
     * 实体新增服务
     */
    private VOInsertService insertService;

    /**
     * 实体修改服务
     */
    private VOUpdateService updateService;

    /**
     * 实体保存服务构造函数
     *
     * @param dao
     *          实体保存数据库器
     */
    public VOSaveService(VOPersistent dao) {
        this.insertService = new VOInsertService(dao);
        this.deleteService = new VODeleteService(dao);
        this.updateService = new VOUpdateService(dao);
    }

    /**
     * 保存实体数组
     *
     * @param vos 实体数组
     * @return  保存后的实体列表
     */
    public List<?> save(SuperVO[] vos) {
        List<SuperVO> list = Arrays.asList(vos);
        return this.save(list);
    }

    /**
     * 保存实体列表
     *
     * @param list 实体列表
     * @return  保存后的实体数组
     */
    @SuppressWarnings("unchecked")
    public List<?> save(List<?> list) {
        List<SuperVO> paralist = (List<SuperVO>) list;

        List<SuperVO> addlist = new ArrayList<SuperVO>();
        List<SuperVO> updatelist = new ArrayList<SuperVO>();
        List<SuperVO> deletelist = new ArrayList<SuperVO>();


        for (SuperVO vo : paralist) {
            if (vo.getStatus() == EntityConst.INSERT || vo.getId() == null) {
                addlist.add(vo);
            } else if (vo.getStatus() == EntityConst.DELETE) {
                deletelist.add(vo);
            } else {
                updatelist.add(vo);
            }
        }
        // 实现批量更新和插入
        if (addlist.size() > 0) {
            this.insertService.insert(addlist);
        }
        if (updatelist.size() > 0) {
            this.updateService.update(updatelist);
        }
        if (deletelist.size() > 0) {
            this.deleteService.delete(deletelist);
        }
        addlist.addAll(updatelist);
        return addlist;
    }
}
